package orm

import (
	"fmt"
	"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/gin/log"
	"gorm.io/driver/sqlserver"
	"gorm.io/gorm"
	"gorm.io/plugin/dbresolver"
	"net/url"
)

type WriterSqlServer struct {
}

func (w WriterSqlServer) Printf(format string, args ...interface{}) {
	// log.Infof(format, args...)
	fmt.Printf(format, args...)
}

var sqlServerDB *gorm.DB
var sqlServerDbMaps = make(map[string]*gorm.DB)

func ConnectSqlServer(MySqlUserName, Password, Address string, Port int, dbName string) *gorm.DB {
	log.Info(dbName + " sqlServer  链接中。。。")
	dsn := fmt.Sprintf("sqlserver://%s:%s@%s:%d?database=%s&encrypt=disable", MySqlUserName, url.PathEscape(Password), Address, Port, dbName)
	db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{
		PrepareStmt: true,
	})
	if err != nil {
		return nil
	}
	log.Info(dbName + " sqlServer  链接成功。")
	db.Use(
		dbresolver.Register(dbresolver.Config{ /* xxx */ }),
		//SetConnMaxIdleTime(time.Hour)
		//SetConnMaxLifetime(24 * time.Hour).
		//SetMaxIdleConns(100).
		//SetMaxOpenConns(200),
	)
	return db
}

func SetSqlServerDb(key string, db *gorm.DB) {
	if db != nil {
		sqlServerDbMaps[key] = db
	}
}

// 获取数据库实例
func GetsqlServerDbMaps() map[string]*gorm.DB {
	return sqlServerDbMaps
}

// 本部oa
func GetSqlServerDB() *gorm.DB {
	return sqlServerDbMaps["hpdi"]
}

// 城规院
func GetSqlServerDBOfCGY() *gorm.DB {
	return sqlServerDbMaps["hpdicgy"]
}

// 桥监
func GetSqlServerDBOfQJ() *gorm.DB {
	return sqlServerDbMaps["hpditmu"]
}

// 大数据
func GetSqlServerDBOfDSJ() *gorm.DB {
	return sqlServerDbMaps["hpdidsjpro"]
}

// 监理
func GetSqlServerDBOfJL() *gorm.DB {
	return sqlServerDbMaps["hpdijl"]
}

// 分公司
func GetSqlServerDBOfFGS() *gorm.DB {
	return sqlServerDbMaps["hpdisub"]
}

// 分公司
func GetAllSqlServerDB() map[string]*gorm.DB {
	return sqlServerDbMaps
}

// 地质平台
// zjsjcx_dba
func GetSqlServerDBOfDZPT() *gorm.DB {
	return sqlServerDbMaps["ZJGH_CityKCloud"]
}
